package com.qf.shoppingcar.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.shoppingcar.entity.Car;
import com.qf.shoppingcar.entity.CarVO;
import com.qf.shoppingcar.mapper.CarMapper;
import entity.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
    @Autowired
    CarMapper carMapper;

    @GetMapping("/all")
    public ResultData all(Integer userId) {
//        QueryWrapper<Car> qw = new QueryWrapper<>();
//        qw.eq("user_id", userId);
//        qw.orderByDesc("create_time");
//        List<Car> products = carMapper.selectList(qw);
//        List<Integer> productIds = new ArrayList<>();
//        StringBuilder productIds = new StringBuilder();
//        for (int i = 0; i < products.size(); i++) {
//            Car car = products.get(i);
//            if (i > 0) {
//                productIds.append(",");
//            }
//            productIds.append(car.getProductId());
//        }
        List<CarVO> all = carMapper.getAllByProductIds(userId);
        return new ResultData<List>(true,all);
    }

    @PostMapping("/putInCar")
    public ResultData putInCar(@RequestBody Car car) {
        String createTime = sdf.format(new Date());
        QueryWrapper<Car> qw = new QueryWrapper<>();
        qw.eq("product_id", car.getProductId());
        qw.eq("user_id", car.getUserId());
        Car car1 = carMapper.selectOne(qw);
        if (car1 != null) {
            car1.setQuantity(car1.getQuantity() + 1);
            car1.setCreateTime(createTime);
            UpdateWrapper<Car> uw = new UpdateWrapper<>();
            uw.eq("product_id", car1.getProductId());
            uw.eq("user_id", car1.getUserId());
            carMapper.update(car1, uw);
            return new ResultData<>(true,"加购成功");
        }
        car.setQuantity(1);
        car.setCreateTime(createTime);
        int insert = carMapper.insert(car);
        if (insert > 0) {
            return new ResultData<>(true,"加购成功");
        } else {
            return ResultData.fail("加购失败");
        }
    }

    @PostMapping("/del")
    public ResultData del(@RequestBody Car car) {
        QueryWrapper<Car> qw = new QueryWrapper<>();
//        qw.eq("id", car.getId());
        int delete = carMapper.deleteById(car.getId());
        if (delete > 0) {
            return new ResultData<>(true,"删除成功");
        } else {
            return ResultData.fail("删除失败");
        }
    }
}
